package it.carlom.stikkyheader.core;

import ohos.agp.components.Component;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.lang.ref.WeakReference;

public class StikkyHeaderUtils {
    public static void executeOnGlobalLayout(Component view, final Runnable runnable) {
        final WeakReference<Component> viewReference = new WeakReference<>(view);
        view.setLayoutRefreshedListener(component -> {
            removeOnGlobalLayoutListener(viewReference.get());
            runnable.run();
        });
    }

    public static void removeOnGlobalLayoutListener(Component view) {
        view.setLayoutRefreshedListener(null);
    }

    public static void setOnTouchListenerOnHeader(@NotNull Component header, @Nullable Component scrollingView, @Nullable final Component.TouchEventListener onTouchListenerOnHeaderDelegate, final boolean allowTouchBehindHeader) {
        if (scrollingView == null || allowTouchBehindHeader) {
            if (onTouchListenerOnHeaderDelegate != null) {
                header.setTouchEventListener(onTouchListenerOnHeaderDelegate);
            }
        }
    }

}
